package com.ctw.tinyservices.id.portal.utils;

import com.ctw.tinyservices.id.common.dto.PageResponseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class JdbcPageUtils {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 返回分页对象
     *
     * @param sql       查询sql
     * @param queryArgs 查询参数
     * @param rowMapper dto mapper
     * @param countSql  总量sql
     * @param countArgs 总量参数
     * @param page      当前页
     * @param size      每页大小
     * @param <T>       dto
     * @return 分页对象
     */
    public <T> PageResponseDTO<T> listPage(String sql, Object[] queryArgs, RowMapper<T> rowMapper,
                                                     String countSql, Object[] countArgs, int page, int size) {

        if (page <= 0) {
            throw new RuntimeException("当前页数必须大于0");
        }
        if (size <= 0) {
            throw new RuntimeException("每页大小必须大于0");
        }
        //总共数量
        int totalSize = jdbcTemplate.queryForObject(countSql, countArgs, Integer.class);

        if (totalSize == 0) {
            return new PageResponseDTO<>();
        }

        //总页数
        int totalPage = totalSize % size == 0 ? totalSize / size : totalSize / size + 1;
        //开始位置
        int offset = (page - 1) * size;
        //return item size
        int limit = size;
        sql = sql + " limit " + limit + " offset " + offset;
        List<T> content = jdbcTemplate.query(sql, queryArgs, rowMapper);
        return new PageResponseDTO<T>(totalSize, totalPage, page, size, content);
    }

}

